<?php
namespace app\admin\controller;
use think\Config;
use think\Controller;
use think\Request;
use think\Session;
use app\admin\model\User as UserModel;

class Base extends Controller
{
    protected $user_id;
    protected $user_name;
    public function _initialize()
    {
        $this->user_id = $this->get_user_id();
        $this->user_name = $this->get_user_name();
        $this->assign('url_route',get_url_route());
        $this->assign('isRoot',$this->isRoot());
        $this->assign('user_name',$this->get_user_name());
    }

    //获取用户id 供前端调用鉴定是否登陆
    public function auth()
    {
        return $this->get_user_id();
    }

    //是否是超级管理员
    public function isRoot()
    {
        return Config::get('root') == $this->get_user_id() ? true : false;
    }

    protected function get_user_id()
    {
        return Session::get('user_id');
    }
    protected function get_user_name()
    {
        return Session::get('user_name');
    }

    //登陆
    public function login(Request $request)
    {
        $name = $request->param("name");
        if(!$name){
            return false;
        }
        $user = UserModel::get(['name'=>$name]);

        if(!$user){
            return false;
        }

        //大爷的账号 必须输入秘钥
        if($user->id == Config::get('root')){
            Session::set('root_name',$name);
            return ajaxReturn(['is_root'=>true]);
        }

        if($user){
            Session::set('user_id',$user->id);
            Session::set('user_name',$name);
            return ajaxReturn(['is_root'=>false,'user_name'=>$name]);
        }else{
            return false;
        }
    }

    //大爷登陆
    public function login_root(Request $request)
    {
        $key = $request->param("key");
        if(!$key || Config::get('root_key') != $key){
            return ajaxReturn('秘钥错误');
        }
        $rootName = Session::get('root_name');
        if(!$rootName){
            return ajaxReturn('访问出错');
        }

        Session::set('user_id',Config::get('root'));
        Session::set('user_name',$rootName);
        return ajaxReturn(['is_root'=>true,'user_name'=>$rootName]);
    }

    public function login_out()
    {
        Session::delete('user_id');
        Session::delete('user_name');
        $this->user_id = '';
        return true;
    }

}
